package SwingUiChatting;

import chattingRoom.ReleaseUtils;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * 使用多线程封装了
 */
public class ClientReceive implements Runnable {

    private Socket client;
    private boolean isRunning;
    private DataInputStream dataInputStream;

    public ClientReceive(Socket client){
        this.client=client;
        try {
            dataInputStream=new DataInputStream(client.getInputStream());
            this.isRunning=true;
        } catch (IOException e) {
            release();
            System.out.println("接收功能的这一块出现了问题");
        }
    }


    public String receiveMessage(){
        String message="";
        try {
            message=dataInputStream.readUTF();
        } catch (IOException e) {
            release();
            System.out.println("接收消息出现了问题");
        }
        return message;
    }

    public void release(){
        this.isRunning=false;
        ReleaseUtils.close(dataInputStream,client);
    }


    @Override
    public void run() {
        while (isRunning){
            String message=receiveMessage();
            if (!message.equals("")){
                //如果接收到的信息不为空，那么就打印处理

                System.out.println(message);
            }
        }
    }
}
